#!/usr/bin/perl -w
#
# Show processlit  to aggregate count
# @param $1 install home
# @param $2 pattern
# @param $3 delimiter
# @param $4 host
# @param $5 port
# @param $6 username
# @param $7 password
# -- Modify  2009.05.26 by DavidLi -split host to get host ip 
# -- Created 2009.05.25 by DavidLi -initial

use strict;
my $SQL="show processlist";
my ($MYSQL_HOME,$RE,$DELIM,$HOST,$PORT,$USER,$PASS) = @ARGV;

my $PARAM="";
$PARAM="$PARAM -h\"$HOST\"" if (defined($HOST) && $HOST ne "");
$PARAM="$PARAM -P\"$PORT\"" if (defined($PORT) && $PORT ne "");
$PARAM="$PARAM -u\"$USER\"" if (defined($USER) && $USER ne "");
$PARAM="$PARAM -p\"$PASS\"" if (defined($PASS) && $PASS ne "");
my $MYSQL= defined ($MYSQL_HOME) ? "$MYSQL_HOME/bin/mysql" : "mysql";
my $MYSQLADMIN= defined $MYSQL_HOME ? "$MYSQL_HOME/bin/mysqladmin" : "mysqladmin";
if ($^O =~ m/MSWin32/) {
  $MYSQL =~ s/\//\\/g;
  $MYSQLADMIN =~ s/\//\\/g;
}
# Check if mysqld is alive
my $retmsg=`$MYSQLADMIN $PARAM ping 2>&1`;
chomp($retmsg);
if ( "$retmsg" ne "mysqld is alive" ) {
    print "em_error=Status${DELIM}Down\n";
    exit 1;
}

my @lines=`$MYSQL -N -s $PARAM --batch  -e"$SQL"`;
#print "@lines";

my $host_ip = "";

foreach my $line (@lines) {
  my $str="";
  chomp $line;
  my @row = split(/\t/,$line);
  
  ###split host domain to get host ip
  if ($row[2] =~ /:/) {
       $host_ip = substr($row[2],0,index($row[2],":"));
  }
  else {
       $host_ip = $row[2];
  }
  my $user_ip=join("@",$row[1],$host_ip);
  ### Id|User@Host|db|Command|State
  print "em_result=$row[0]|$user_ip|$row[3]|$row[4]|$row[6]\n"
}
